//
//  LandingViewController.m
//  Text_ problem
//
//  Created by jiboxue on 13-1-10.
//  Copyright (c) 2013年 jiboxue. All rights reserved.
//

#import "LandingViewController.h"
#import "PMAPI.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "json.h"
#import "CustomerInformation.h"
#import "Reachability.h"
#import <QuartzCore/QuartzCore.h>

@interface LandingViewController ()

@end

@implementation LandingViewController
@synthesize imageView_wifi;
@synthesize imageView_landing;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _activityView = [[UIView alloc]init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    [self login];
    [self wifi];
    self.textFieldLandingUserName = [[[UITextField alloc]initWithFrame:CGRectMake(162, 208, 253, 45)]autorelease];
    self.textFieldLandingUserName.borderStyle = UITextBorderStyleRoundedRect;
    self.textFieldLandingUserName.placeholder = @"User name";
    self.textFieldLandingUserName.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    self.textFieldLandingUserName.clearButtonMode = YES;
    self.textFieldLandingUserName.delegate = self;
    [imageView_landing addSubview:self.textFieldLandingUserName];
    
    self.textFieldLandingPassword = [[[UITextField alloc]initWithFrame:CGRectMake(162, 280, 253, 45)]autorelease];
    self.textFieldLandingPassword.borderStyle = UITextBorderStyleRoundedRect;
    self.textFieldLandingPassword.keyboardType = UIKeyboardTypeNumberPad;
    self.textFieldLandingPassword.placeholder = @"Password";
    self.textFieldLandingPassword.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [self.textFieldLandingPassword setSecureTextEntry:YES];
    self.textFieldLandingPassword.clearButtonMode = YES;
    self.textFieldLandingPassword.delegate = self;
    [imageView_landing addSubview:self.textFieldLandingPassword];
    
    _activityView.frame = CGRectMake(imageView_landing.frame.size.width/2-60, imageView_landing.frame.size.height/2-60, 120, 120);
    _activityView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
    UIActivityIndicatorView *activity = [[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]autorelease];
    activity.frame = CGRectMake(_activityView.frame.size.width/2-25, _activityView.frame.size.height/2-25, 50, 50);
    [activity startAnimating];
    [_activityView addSubview:activity];
    _activityView.layer.cornerRadius = 8;
    _activityView.layer.masksToBounds = YES;
}
-(void)login
{
    imageView_landing = [[UIImageView alloc]initWithFrame:CGRectMake(223.5, 95.5, 577, 577)];
    imageView_landing.image = [UIImage imageNamed:@"sign_in_background.png"];
    imageView_landing.userInteractionEnabled = YES;
    [self.view addSubview:imageView_landing];
    [imageView_landing release];
    
    button_landing = [UIButton buttonWithType:UIButtonTypeCustom];
    button_landing.frame = CGRectMake(160, 370, 260, 61);
    [button_landing setBackgroundImage:[UIImage imageNamed:@"sign_in.png"] forState:UIControlStateNormal];
    [button_landing addTarget:self action:@selector(buttonLanding) forControlEvents:UIControlEventTouchUpInside];
    [imageView_landing addSubview:button_landing];
    
}
-(void)wifi
{
    imageView_wifi = [[UIImageView alloc]initWithFrame:CGRectMake(233.5, 95.5, 577, 577)];
    imageView_wifi.image = [UIImage imageNamed:@"all_login failed.png"];
    imageView_wifi.alpha = 0;
    imageView_wifi.userInteractionEnabled = YES;
    [self.view addSubview:imageView_wifi];
    
    button_wifi = [UIButton buttonWithType:UIButtonTypeCustom];
    button_wifi.frame = CGRectMake(228, 395, 117, 47);
    [button_wifi setBackgroundImage:[UIImage imageNamed:@"btn_retry.png"] forState:UIControlStateNormal];
    [button_wifi addTarget:self action:@selector(buttonRetry) forControlEvents:UIControlEventTouchUpInside];
    [imageView_wifi addSubview:button_wifi];
}
- (void)buttonRetry
{
    if ([self isOnline]) {
        [self.view addSubview:_activityView];
        if ([self checkUsernameAndPassword]) {
            [self.view removeFromSuperview];
        }
        else
        {
            imageView_landing.alpha = 1;
            imageView_wifi.alpha = 0;
        }
        [_activityView removeFromSuperview];
    }
    else
    {
        [self showInfo:@"please manually re-connect internet"];
    }
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    [_activityView removeFromSuperview];
    // Use when fetching text data
    //    NSString *responseString = [request responseString];
    
    // Use when fetching binary data
    //    NSData *responseData = [request responseData];
    
    
    NSMutableDictionary *usernameInfo = [request.responseString JSONValue];
    [usernameInfo setObject:_username forKey:@"username"];
//    [CustomerInformation save:usernameInfo];
    NSMutableDictionary *passwordInfo = [request.responseString JSONValue];
    [passwordInfo setObject:_password forKey:@"password"];
//    [CustomerInformation save:passwordInfo];
    
    
    //    [self showInfo:@"登陆成功"];
    imageView_landing.alpha = 1;
    imageView_wifi.alpha = 0;
    
    NSDictionary *dictionaryMessage = [[request responseString] JSONValue];
    [dictionaryMessage setValue:_textFieldLandingPassword.text forKey:@"password"];
    NSLog(@"第一次登陆时 ＝ %@",dictionaryMessage);
    [CustomerInformation save:dictionaryMessage];
    
    NSString *deviceTokenString = [[NSUserDefaults standardUserDefaults] stringForKey:@"deviceTokenString"];
    if ([deviceTokenString length] > 0) {
        ASIHTTPRequest *tokenRequest =
        [PMAPI registerNotification:deviceTokenString
                        andUsername:_textFieldLandingUserName.text
                        andPassword:_textFieldLandingPassword.text];
        
        [tokenRequest startAsynchronous];
    }
    
    [self.view removeFromSuperview];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    [_activityView removeFromSuperview];
    //    NSError *error = [request error];
    if ([self isOnline]) {
        [self showInfo:@"please enter the correct username and password"];
    }
    else{
        imageView_landing.alpha = 0;
        imageView_wifi.alpha = 1;
        [self showInfo:@"please manually re-connect internet"];
    }
}
- (BOOL)isOnline
{
    
    BOOL isExistenceNetwork = YES;
    Reachability *r = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork=NO;
            //   NSLog(@"没有网络");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork=YES;
            //   NSLog(@"正在使用3G网络");
            break;
        case ReachableViaWiFi:
            isExistenceNetwork=YES;
            //  NSLog(@"正在使用wifi网络");
            break;
    }
    return isExistenceNetwork;
}
-(void)buttonLanding
{
//    [imageView_landing addSubview:_activityView];
    
    if ([self.textFieldLandingPassword.text length] == 0 ||[self.textFieldLandingPassword.text length] == 0)
    {
        [self showInfo:@"Username and password can't be empty"];
    }
    else
    {    
        [imageView_landing addSubview:_activityView];
        [self.textFieldLandingPassword resignFirstResponder];
        [self.textFieldLandingPassword resignFirstResponder];
        _username = self.textFieldLandingPassword.text;
        _password = self.textFieldLandingPassword.text;
        ASIHTTPRequest *request =
        [PMAPI requestLoginUsername:_textFieldLandingUserName.text
                        andPassword:_textFieldLandingPassword.text];
    
        [request setDelegate:self];
        [request startAsynchronous];
    }
}
-(void)showInfo:(NSString *)textMessage
{
    UIAlertView *alertView =
    [[UIAlertView alloc] initWithTitle:@"Alert"
                               message:textMessage
                              delegate:self
                     cancelButtonTitle:@"OK"
                     otherButtonTitles:nil];
    
    [alertView show];
    [alertView release];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.view.frame = CGRectMake(0, -60, 1024, 768);
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    self.view.frame = CGRectMake(0, 0, 1024, 768);
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}
- (BOOL)checkUsernameAndPassword
{
    NSLog(@"4444");
    BOOL result = NO;
    NSDictionary *dictionaryUserInfo = [CustomerInformation userMessage];
    NSLog(@"sdsadasdsad%@",dictionaryUserInfo);
    if (dictionaryUserInfo) {
        NSLog(@"555");
        NSString *username = [dictionaryUserInfo objectForKey:@"username"];
        //这个没有
        NSString *password = [dictionaryUserInfo objectForKey:@"password"];
        NSLog(@"username%@",username);
        NSLog(@"password%@",password);
        ASIHTTPRequest *request = [PMAPI requestLoginUsername:username andPassword:password];
        [request startSynchronous];
        
        if ([request responseStatusCode] == 401) {
            [CustomerInformation clear];
            return NO;
        }
        else
        {
            NSMutableDictionary *userInfo = [request.responseString JSONValue];
            [userInfo setObject:password forKey:@"password"];
            [CustomerInformation save:userInfo];
            return YES;
        }
    }
    return result;
}

-(void)dealloc
{
    [imageView_landing release];
    [imageView_wifi release];
    [_activityView release];
    [_username release];
    [_password release];
    self.textFieldLandingUserName = nil;
    self.textFieldLandingPassword = nil;
    
    [super dealloc];
}
@end
